<?php

namespace app\console\controller;

namespace app\console\controller;

use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\Lipei as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;

class Lipei extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'clearCache' => ['only'],
    ];


    /**
     * 广告位列表
     */
    public function index($p = 10)
    {
        $where = [];
        $param = Request::instance()->param();
        if(!empty($param['title'])) $where['c.username|c.tel|c.car_number|c.brand_type|c.engine_number'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode(' / ', $param['interval_timer']);
            $where['c.create_time'] = ['between time', [strtotime($interval_timer[0]), strtotime($interval_timer[1])]];
        }

        $data = (new \app\console\model\Lipei())->alias('c')->where($where)->join('member m','c.member_id = m.id','left')->field('c.*')->order('id','desc')->paginate($p,false,['query' => $param])->each(function($item,$key){
            if(session('role_id') != 1){
                $item->phone = hideStr($item->phone,1,6);
            }
        });

        if(isset($param['export'])){
            $this->push_coupon($data);
        }
        return $this->fetch('', [
            'data' => $data,

        ]);
    }

    public function push_coupon($data,$name = '车库记录导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '用户账户')
            ->setCellValue('B1', '手机号码')
            ->setCellValue('C1', '车主姓名')
            ->setCellValue('D1', '身份证号')
            ->setCellValue('E1', '车辆牌号')
            ->setCellValue('F1', '车辆型号')
            ->setCellValue('G1', '发动机号')
            ->setCellValue('H1', '品牌型号')
            ->setCellValue('I1', '车辆识别码')
            ->setCellValue('J1', '检测有效期')
            ->setCellValue('K1', '机动车强险承保日期')
            ->setCellValue('L1', '机动车商业险承保日期')
            ->setCellValue('M1', '注册日期')
            ->setCellValue('N1', '创建日期')
        ;

        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, "\t".$v['username']."\t")
                ->setCellValue('B' . $num, "\t".$v['phone']."\t")
                ->setCellValue('C' . $num, $v['car_name'])
                ->setCellValue('D' . $num, "\t".$v['id_number']."\t")
                ->setCellValue('E' . $num, $v['car_number'])
                ->setCellValue('F' . $num, $v['car_model'])
                ->setCellValue('G' . $num, $v['engine_number'])
                ->setCellValue('H' . $num, $v['brand_number'])
                ->setCellValue('I' . $num, $v['id_code'])
                ->setCellValue('J' . $num, $v['test_time'])
                ->setCellValue('K' . $num, $v['destory_time'])
                ->setCellValue('L' . $num, $v['car_business_time'])
                ->setCellValue('M' . $num, $v['register_time'])
                ->setCellValue('N' . $num, $v['create_time'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('车库记录导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }



    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }
        $data = Db::name('car c')->where($where)->join('member m','c.member_id = m.id','left')->field('c.*,m.username')->paginate(10,false,['query' => $param]);
        return $this->fetch('create', ['shop_id' => $shop_id

        ]);

    }


    /**
     * 广告位编辑
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            // 验证

           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());
            //理赔附表
            $dispose = (new \app\console\model\Lipei())->allowField(true)->save($data,['id' => $id]);
            if(!empty($data['lipei_id'])){
                $find = Db::name('lipei_process')->where(['lipei_id' => $id,'lipei_type_id' => $data['lipei_id']])->find();
                if(!empty($find)){
                    fail('此流程已添加过');
                }
                Db::name('lipei_process')->insert(['lipei_id' => $id,'lipei_type_id' => $data['lipei_id'],'create_time' => date('Y-m-d H:i:s',time())]);
            }

            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }
            fail('操作失败');
        }

        $data = Db::name('lipei c')->where('c.id',$id)->join('member m','c.member_id = m.id','left')->field('c.*')->find();
        if(session('role_id') != 1){
            $data['username'] = hideStr($data['username'],1,6);
        }
        $lipei_data = Db::name('lipei_process')
            ->alias('lp')
            ->field('lp.*')
            ->where('lipei_id',$data['id'])
            ->select();
        return $this->fetch('create', [
            'data' => $data,
            'item' => $data,
            'lipei_data' => $lipei_data
        ]);
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
            auding_status($id,'title');
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }





    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            (new AdTypeModel)->where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('AdType/index'));
    }

    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}